package com.dongss.study.service;

import com.dongss.study.dao.UserDAO;
import com.dongss.study.dao.UserRoleAssignmentDAO;
import com.dongss.study.domain.User;
import com.dongss.study.domain.UserRoleAssignment;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * Created by dongshuanshuan on 17-7-30.
 */
@Service
@Transactional
public class UserRoleAssignmentService {

    @Resource
    UserRoleAssignmentDAO userRoleAssignmentDAO;

    @Resource
    UserDAO userDAO;

    @Resource
    UserService userService;


    public List<UserRoleAssignment> findUserRoleAssignmentsByUsername(String username){

        List<UserRoleAssignment> result=new ArrayList<>();

        User user=userService.findByName(username);
        Map<String, Object> params = new HashMap<>();
        params.put("user", user);
        result=userRoleAssignmentDAO.find("from UserRoleAssignment assign where assign.user = :user",params);

        return result;
    }

    public Set<String> findRoleNamesByUsername(String username){
        Set<String> roleNames=new HashSet<>();
        List<UserRoleAssignment> userRoles=findUserRoleAssignmentsByUsername(username);
        for(UserRoleAssignment userRole:userRoles){
            roleNames.add(userRole.getRole().getName());
        }
        return roleNames;
    }

    public void create(UserRoleAssignment userRole){
        userRoleAssignmentDAO.save(userRole);
    }

    public void update(UserRoleAssignment userRole){
        userRoleAssignmentDAO.update(userRole);
    }

    public void delete(UserRoleAssignment userRole){
        userRoleAssignmentDAO.delete(userRole);
    }

    public UserRoleAssignment find(Integer id){
        return userRoleAssignmentDAO.get(id);
    }
}
